<?

require_once ('config.php');

if ($argc <= 1) {
	print("Please provide the XML filename as a command-line argument:\n");
	print("\tphp -f xml2json_test.php test1.xml\n");
	return;
} else {
	$testXmlFile = $argv[1];
}

if (file_exists($testXmlFile)) {
	exec ('rm oldiprr.xml', $null, $exec_status);
}

#exec ('rm oldiprr.xml', $null, $exec_status);
exec ('wget http://www.oldi.ru/price/oldiprx.zip -o /dev/null -O oldiprx.zip && unzip oldiprx.zip', $null, $exec_status);
exec ('rm oldiprx.zip', $null, $exec_status);


file_exists($testXmlFile) or die('Could not find file ' . $testXmlFile);
if (!($fp = fopen($testXmlFile, "r"))) {
    die("could not open XML input");
}


function ff_sql_query ($query_text) {
	if (DEBUG) 
		echo $query_text . PHP_EOL;
	$result_2 = mysql_query($query_text);
	if (!$result_2) {
		echo 'Invalid query: ' . mysql_error() . PHP_EOL;
	}
	return $result_2;
}

function my_xml_parse ($data, $end_of_file) {
	global $tmp_vars,$goods;
/*	if (isset ($tmp_vars['item_id'])) {
		//$item = $tmp_vars['item_id'];
	}
*/
	$begin_product_id = '<good privateid';
	$end_product_id = '</good>';
	$begin_name = '<name>';
	$end_name = '</name>';
	$begin_price = '<price currencyid="643" id="MC00000016" name="Кол1 (руб)">';
	$end_price = '</price>';
	$begin_available = '<available id="00011">';
	$end_available = '</available>';
	$begin_volume = '<volume>';
	$end_volume = '</volume>';
	$begin_weight = '<weight>';
	$end_weight = '</weight>';
	if (!$end_of_file) {
		$pos_1 = stripos ($data, $begin_product_id);
		if ($pos_1 !== false) {
			$pos_2 = stripos ($data, '"');
			$pos_3 = stripos (substr($data, strlen($begin_product_id)+3), '"');
			//echo $pos_1 . ' ' . $pos_2 . ' ' . $pos_3 . PHP_EOL;
			$tmp_vars['item_id'] = substr($data, $pos_2+1, $pos_3);
		}
		$pos_4 = stripos ($data, $end_product_id);
		if ($pos_4 !== false) {
			$goods[$tmp_vars['item_id']]['name'] = $tmp_vars['name'];
			$goods[$tmp_vars['item_id']]['price'] = $tmp_vars['price'];
			$goods[$tmp_vars['item_id']]['available'] = $tmp_vars['available'];
			$goods[$tmp_vars['item_id']]['volume'] = $tmp_vars['volume'];
			$goods[$tmp_vars['item_id']]['weight'] = $tmp_vars['weight'];
			$tmp_vars = null;
		}
		$pos_5 = stripos ($data, $begin_name);
		if ($pos_5 !== false) {
			$pos_6 = stripos ($data, $end_name);
			if ($pos_6 !== false) {
				$tmp_vars['name'] = htmlspecialchars_decode( substr($data,$pos_5+strlen($begin_name),$pos_6 - $pos_5 - strlen($begin_name)));
			}
		}
		$pos_7 = stripos ($data, $begin_price);
		if ($pos_7 !== false) {
			$pos_8 = stripos ($data, $end_price);
			if ($pos_8 !== false) {
				$tmp_vars['price'] = substr($data,$pos_7+strlen($begin_price),$pos_8 - $pos_7 - strlen($begin_price));
			}
		}
		$pos_10 = stripos ($data, $begin_available);
		if ($pos_10 !== false) {
			$pos_11 = stripos ($data, $end_available);
			if ($pos_11 !== false) {
				$tmp_vars['available'] = substr($data,$pos_10+strlen($begin_available),$pos_11 - $pos_10 - strlen($begin_available));
			}
		}
		$pos_12 = stripos ($data, $begin_volume);
		if ($pos_12 !== false) {
			$pos_13 = stripos ($data, $end_volume);
			if ($pos_13 !== false) {
				$tmp_vars['volume'] = substr($data,$pos_12+strlen($begin_volume),$pos_13 - $pos_12 - strlen($begin_volume));
			}
		}
		$pos_14 = stripos ($data, $begin_weight);
		if ($pos_14 !== false) {
			$pos_15 = stripos ($data, $end_weight);
			if ($pos_15 !== false) {
				$tmp_vars['weight'] = substr($data,$pos_14+strlen($begin_weight),$pos_15 - $pos_14 - strlen($begin_weight));
			}
		}
	}
	return true;
}

while ($data = fgets($fp)) {
    if (!my_xml_parse($data, feof($fp))) {
        echo "<br>Error: ";
        break;
    }
}

if (!empty ($goods)) {
	$html_out = '';
	$link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
	if (!$link) {
		die('Не удалось соединиться : ' . mysql_error());
	}
	// выбираем foo в качестве текущей базы данных
	$db_selected = mysql_select_db(DB_NAME, $link);
	if (!$db_selected) {
		die ('Не удалось выбрать базу foo: ' . mysql_error());
	}

	$result = mysql_query("SET NAMES 'latin1'");

	$has_new = 0;
	foreach ($goods as $oldi_code => $oldi_item) {
/*		echo $oldi_code . PHP_EOL;
		print_r ($oldi_item);
		echo PHP_EOL;
*/
		$sql_query = "SELECT id FROM " . DB_TABLE_CATALOG . " WHERE `privateid` = '" . $oldi_code . "' limit 1";
		$result = ff_sql_query ($sql_query);
		if (mysql_num_rows($result) === 1) {
		}
		else {
			$has_new = 1;
			if (DEBUG) {
				echo "New item: " . $oldi_item['name'] . ' price: ' . $oldi_item['price'] . PHP_EOL;
			}
			$html_out .= "New item: " . $oldi_item['name'] . ' price: ' . $oldi_item['price'] . '<br>' . PHP_EOL;
			$html_out .= "<a href='http://www.oldi.ru/catalog/element/" . $oldi_code . "/'>" . $oldi_item['name'] . '</a><br><br>' . PHP_EOL;
		}
		$sql_query = "INSERT INTO " . DB_TABLE_CATALOG . " (`privateid`, `price`) VALUES (" . 
		"'" . mysql_real_escape_string($oldi_code) . "'" . 
		", '" . mysql_real_escape_string(str_replace (',','.', $oldi_item['price'])) . "'" . 
		")";
		ff_sql_query ($sql_query);
		
		
		
	}
	if ($has_new) {
		$from = EMAIL_ADMIN;
		$headers = "From:" . EMAIL_ADMIN . "\r\n" .
			'X-Mailer: PHP/' . phpversion() . "\r\n" .
			'Content-Type: text/html; ' . "\r\n";
		mail(EMAIL_ADMIN, 'OLDI report', '<html><body>'.$html_out.'</body></html>',$headers);
	}
}

?>
